/**
 * @author Kelvin Qi
 */
var Rows = 8;
var Cells = 15;
var squareEdgeLen = 50;	//square side
var BorderWidth = 1;
var TOTAL_TIMER = 250;
var Times = TOTAL_TIMER;
var CONTENT_LEFT = 5;	//px
var CONTENT_TOP = 65;	//px
var realyTop = 100;
var level;
var passEatenNum;
var eatenNum;
var totalEatenNum = 0;
var scoreNum;
var startFlag = false;
function set_Timer() {
	Times = TOTAL_TIMER - 3*level*level;
}
function setPassEatenNum() {
	passEatenNum = 4 + level;
}
//create the map
var Map = new Array();
var Sx;	//the x-index of snake
var Sy;	//the y-index of snake
function CreateMap(){
    BW = eval(Cells * squareEdgeLen + 2 * BorderWidth);	//width of the map
    BH = eval(Rows * squareEdgeLen + 2 * BorderWidth);	//height of the map
    CONTENT_LEFT = (document.body.clientWidth - BW)/2;
    realyTop = document.body.clientHeight - BH - CONTENT_TOP;
    if(realyTop > 0) {
    	realyTop = parseInt(realyTop/2);
    	realyTop += CONTENT_TOP;
    }
    var CONTENT_INNER_HTML = '';
    CONTENT_INNER_HTML = '<div id="MainMap" style="position:absolute; display:none; left:';
    CONTENT_INNER_HTML += (CONTENT_LEFT+'px; top:'+ realyTop +'px; width:' + BW + 'px;height:'); 
    CONTENT_INNER_HTML += (BH + 'px;border-width:' + BorderWidth + 'px;border-style:outset;border-color:#005EAC;"></div>');
    document.getElementById("content").innerHTML = CONTENT_INNER_HTML;
    for (y = 0; y < Rows; y++) {
        Map[y] = new Array();
        for (x = 0; x < Cells; x++) {
			//init the boxs, '0' means this is a blank box.
			Map[y][x] = '0';
		}
    }
    Sx = parseInt(Math.random() * (Cells - 2)) + 1;
    Sy = parseInt(Math.random() * (Rows - 2)) + 1 ;
    CreateSnake();	//snake box - div
    CreatFood(); 	//food box - span
    AllDiv = document.getElementById("MainMap").getElementsByTagName("div");
    AllSpan = document.getElementById("MainMap").getElementsByTagName("span");
}

function CreateSnake(){
	var MainMapInnerHTML = '<div x=' + Sx + ' y=' + Sy + ' style="position:absolute; left:' + Sx * squareEdgeLen + 'px; ';
	MainMapInnerHTML += 'top:' + Sy * squareEdgeLen + 'px; width:' + squareEdgeLen + 'px; height:' + squareEdgeLen + 'px; ';
	MainMapInnerHTML += 'overflow:hidden; background-color:red;background-image:url(' + url_owner +')"></div>';
    document.getElementById("MainMap").innerHTML += MainMapInnerHTML; 
    Map[Sy][Sx] = 'S' ;	//'S' means Map [Sy][Sx] is a snake
}

function CreatFood(){
    Fx = parseInt(Math.random() * Cells);
    Fy = parseInt(Math.random() * Rows);
    if (Map[Fy][Fx] == '0') {	//if it's a blank box
		var randomFIndex = Math.round( Math.random() * (friends.length - 1));
		var randomFName = friends[randomFIndex].getDisplayName();
		var randomFImg = friends[randomFIndex].getField(opensocial.Person.Field.THUMBNAIL_URL);
		var Fleft = Fx * squareEdgeLen;
		var Ftop = Fy * squareEdgeLen;
		var MainMapInnerHTML = '<span style="position:absolute;left:' + Fleft + 'px;top:' + Ftop + 'px;width:' + squareEdgeLen;
		MainMapInnerHTML += 'px;height:' + squareEdgeLen;
		MainMapInnerHTML += 'px;overflow:hidden; background-color:green;background-image:url(';
		MainMapInnerHTML += randomFImg +');"></span>';
        document.getElementById("MainMap").innerHTML += MainMapInnerHTML;
		document.getElementById('fname').style.left = ((Fleft + CONTENT_LEFT -10) + "px");
        document.getElementById('fname').style.top = ((Ftop + realyTop - 14) + "px");
		document.getElementById("fname").innerHTML = randomFName;
        Map[Fy][Fx] = 'F';
    }
    else {
        CreatFood();	//unless find one blank box
	}
}

function Move(){
	Sx += GoX;
    Sy += GoY;
    if (Sy < 0 || Sy >= Rows){ //touch the boder, game over
        Move1();
	}
    else {
        SnakeFront = Map[Sy][Sx];
        if (SnakeFront == '0') { //a blank box
            Move2();
			scoreNum ++;
		}
        else {
            if (SnakeFront == 'F') {//a food box
                Move3();
				scoreNum += 20;
				eatenNum++;
				totalEatenNum++;
				Times -= parseInt((6*level + 3)/passEatenNum);
				if(eatenNum >= passEatenNum) {
					eatenNum = 0;
					level++;
					set_Timer();
					setPassEatenNum();
				}
			}
            else {
                Move1();
        	}
		}
    }
    refreshScore();
}

function Move2(){
    Map[AllDiv[0].getAttribute("y")][AllDiv[0].getAttribute("x")] = '0' //蛇走开后，把原位置设置为'0'，表示是空地
    document.getElementById("MainMap").removeChild(AllDiv[0]);
    CreateSnake();//在新的位置生成蛇的<div>
    setTimeout('Move()', Times); //再次移动
}

function Move3(){
    CreateSnake(); //蛇数组当前元素不删除，<div>累加一次，蛇长长一节
    //AllSpan[0].removeNode(true) //把食物数组当前元素删除，在下面的 CreatFood()语句重新生成
    document.getElementById("MainMap").removeChild(AllSpan[0]);
    CreatFood(); //再次随机生成食物
    setTimeout('Move()', Times); //再次移动
}

function KeyDown(ev){
	if(!startFlag) {
		return false;
	}
    ev = ev || window.event;
    Key = ev.keyCode;
    switch (Key) {
        //case 37:
		case 65:
            Dir(-1, 0);
			ev.returnValue   =   false;
            break; //left
        //case 39:
		case 68:
            Dir(1, 0);
			ev.returnValue   =   false;
            break; //right
        //case 38:
		case 87:
            Dir(0, -1);
			ev.returnValue   =   false;
            break;//up
        //case 40:
		case 83:
            Dir(0, 1);
			ev.returnValue   =   false;
            break;//down
    } 
    return false;
}

var Star = 0;
function Dir(x, y){
    GoX = x;
    GoY = y;
    if (Star == 0) {
        Star = 1;
        Move();
    }
}

function chgCursorHand(){
	document.body.style.cursor = "hand";
}

function chgCursorDefault(){
	document.body.style.cursor = "default";
}

function initScore() {
	scoreNum = 0;
}

function startGame() {
	document.getElementById("startGame").innerHTML = "";
	Times = TOTAL_TIMER;
	scoreNum = 0;
	level = 0;
	eatenNum = 0;
	totalEatenNum = 0;
	startFlag = true;
	initScore();
	initDir();
	set_Timer();
	setPassEatenNum();
	document.getElementById("gameOver").innerHTML = "";
	document.getElementById("rankInformation").innerHTML = "";
	document.getElementById("restart").innerHTML = "";
	document.getElementById('MainMap').style.display = "block";
    refreshScore();
}

function refreshScore() {
	document.getElementById("score").innerHTML = "得分:";
	document.getElementById("scoreNum").innerHTML = "<b>"+ scoreNum +"</b>";
	document.getElementById("timer").innerHTML = '&nbsp;&nbsp;当前速度:<b>' + ((1000/Times).toFixed(2)) + '</b>';
	document.getElementById("eatenNum").innerHTML = '&nbsp;&nbsp;本关吃掉好友数:<b>' + eatenNum + '</b>&nbsp;&nbsp;一共吃掉好友数:<b>'+ totalEatenNum+'</b>';
    document.getElementById("timer").innerHTML = '&nbsp;&nbsp;当前速度:<b>' + ((1000/Times).toFixed(2)) + '</b>';
	document.getElementById("level").innerHTML = '&nbsp;&nbsp;等级:<b>' + level + '</b>&nbsp;&nbsp;升级到下一关需吃好友数:<b>' + passEatenNum + '</b>';
}

//init the direction of the snake when the user click 'start'
function initDir() {
	var x;
	var y;
	var vx = Cells > 2*Sx ? Sx : Cells - Sx;
	vx /= Cells;
	var vy = Rows > 2*Sy ? Sy : Rows - Sy;
	vy /= Rows;
	var vy = (Sy/Rows);
	if(vx > vy) {
		x = 0;
		y = Rows > 2*Sy ? 1 : -1;
	} else {
		x = Cells > 2*Sx ? 1 : -1;
		y = 0;
	}
	Dir(x,y);
}

//Game over
function Move1(){
	startFlag = false;
	document.getElementById("gameOver").innerHTML = '&nbsp;&nbsp;&nbsp;本次游戏一共吃掉了<span style="color:red">'+ totalEatenNum +'</span>位好友，获得<span style="color:red">' + scoreNum +'</span>分。';
	makePOSTRequest();
}

function restart() {
	Star = 0;
	document.getElementById("content").removeChild(document.getElementById("MainMap"));
	CreateMap();
	startGame();
}

if (window.addEventListener) {//for Firefox or Chrome
    window.addEventListener('keydown', KeyDown, false);
}
else {//for IE
    document.attachEvent("onkeydown", this.KeyDown);
}